package problems

// 1006
// https://leetcode-cn.com/problems/clumsy-factorial/
func Clumsy(N int) int {
	arr := []int{0, 1, 2, 6, 7, 7, 8, 6}
	if N < 8 {
		return arr[N]
	}
	res := 0
	res, N = N*(N-1)/(N-2), N-3
	switch N % 4 {
	case 1:
		return res
	case 2:
		return res + 1
	case 3:
		return res + 1
	default:
		return res - 2
	}
}

// 1021
// https://leetcode-cn.com/problems/remove-outermost-parentheses/
func RemoveOuterParentheses(S string) string {
	var res []byte
	var index, num = 0, 0
	for i := 0; i < len(S); i++ {
		if S[i] == '(' {
			num++
		} else {
			num--
		}
		if i != 0 && num == 0 {
			res = append(res, S[index+1:i]...)
			index = i + 1
		}
	}
	return string(res)
}

// 1022
// https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers/
func SumRootToLeaf(root *TreeNode) int {
	var sum int
	var order func(root *TreeNode, num int)
	order = func(root *TreeNode, num int) {
		if root != nil {
			num = num<<1 + root.Val
			if root.Left == nil && root.Right == nil {
				sum += num
			} else {
				order(root.Left, num)
				order(root.Right, num)
			}
		}
	}
	order(root, 0)
	return sum
}

// 1047
// https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
func RemoveDuplicates2(S string) string {
	bs := make([]byte, 0)
	for i := 0; i < len(S); i++ {
		if len(bs) > 0 && bs[len(bs)-1] == S[i] {
			bs = bs[:len(bs)-1]
		} else {
			bs = append(bs, S[i])
		}
	}
	return string(bs)
}
